﻿#region

using System;
using System.Linq;
using CuongHanh.Context;
using CuongHanh.DAL;
using CuongHanh.Models;

#endregion

namespace CuongHanh.Service
{
    public class PriceHistoryService : BaseService
    {
        public static string Gets(int start,
                int limit,
                string q)
        {
            using (UnitOfWork unitOfWork = new UnitOfWork())
            {
                IOrderedQueryable<PriceHistory> query = unitOfWork.Where<PriceHistory>(c => !c.Inactive).OrderByDescending(c => c.LastModified);
                return FormatResult(query.Count(),
                        query.OrderByDescending(c => c.LastModified).Skip(start).Take(limit));
            }
        }

        public static PriceHistory Get(int id)
        {
            using (UnitOfWork unitOfWork = new UnitOfWork())
            {
                return unitOfWork.GetById<PriceHistory>(id);
            }
        }

        public static UpdateResult Insert(PriceHistory model)
        {
            using (UnitOfWork unitOfWork = new UnitOfWork())
            {
                try
                {
                    double percent = model.PercentForUpPrice / 100 + 1;
                    var styleMaterials = unitOfWork.Where<StyleMaterial>();
                    foreach (var item in styleMaterials)
                    {
                        item.Price = Math.Round(item.Price * percent, 2);
                        CacheList<StyleMaterial>.Singleton.UpdateCache(item);

                    }

                    var styleStones = unitOfWork.Where<StyleStone>();
                    foreach (var item in styleStones)
                    {
                        item.Price = Math.Round(item.Price * percent, 2);
                        CacheList<StyleStone>.Singleton.UpdateCache(item);

                    }
                    var parentMaterial = unitOfWork.Where<ParentMaterial>();
                    foreach (var item in parentMaterial)
                    {
                        item.Price = Math.Round(item.Price * percent,2);
                        Cache3Key<ParentMaterial>.Singleton.UpdateCache(item);

                    }
                    model.LastModified = DateTime.Now;
                    unitOfWork.Insert(model);
                    unitOfWork.Save();
                    CacheContext<PriceHistory>.Singleton.UpdateCached(model);
                    return new UpdateResult(1,
                        string.Format("Insert PriceHistory {0} successful!",
                                model.Id));
                }
                catch (Exception ex)
                {
                    return new UpdateResult(4,
                        string.Format("Insert PriceHistory Percent For Up Price {0} error!",
                                model.PercentForUpPrice));
                }
            }
        }
    }
}
